package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends
        ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    //会员登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1获取手机号、验证码验空
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String openid = loginVo.getOpenid();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(20001,"数据为空");
        }
        //2 校验验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!code.equals(redisCode)){
            throw new YyghException(20001,"验证码有误");
        }

        Map<String, Object> map = new HashMap<>();
        //2.5 根据openid为空，走登录注册流程
        if(StringUtils.isEmpty(openid)){
            //3 根据手机号查询用户
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if(userInfo==null){
                //4 查询用户为空，走注册步骤
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                this.save(userInfo);
            }
            //5 验证用户是否被锁定
            if(userInfo.getStatus() == 0) {
                throw new YyghException(20001,"用户已经禁用");
            }
            //6补全信息
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //7 完成登录步骤
            String token = JwtHelper
                    .createToken(userInfo.getId(), userInfo.getName());
            map.put("token", token);
        }else{
            //8根据openid不为空，绑定手机号
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid",openid);
            UserInfo userInfowx = baseMapper.selectOne(wrapper);
            if(userInfowx==null){
                throw  new YyghException(20001,"微信注册有误");
            }

            userInfowx.setPhone(phone);
            baseMapper.updateById(userInfowx);
            //判断用户是否锁定
            if(userInfowx.getStatus()==0){
                throw  new YyghException(20001,"用户已被禁用");
            }
            //6补全信息
            String name = userInfowx.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfowx.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfowx.getPhone();
            }
            map.put("name", name);

            //7 完成登录步骤
            String token = JwtHelper
                    .createToken(userInfowx.getId(), userInfowx.getName());
            map.put("token", token);
        }
        return map;

    }

    //传递参数提交用户认证信息
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据userId查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //把认证信息存入用户信息，更新数据
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    //根据用户id获取用户信息接口
    @Override
    public UserInfo getUserInfoById(Long userId) {
        UserInfo userInfo = this.packUserInfo(baseMapper.selectById(userId));
        return userInfo;
    }

    //带条件带分页查询用户列表
    @Override
    public IPage<UserInfo> selectPage(IPage<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //1从vo取出查询条件
        String name = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        //2根据参数判断拼写sql
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //3查询结果
        IPage<UserInfo> pageModel = baseMapper.selectPage(pageParam, wrapper);
        pageModel.getRecords().stream().forEach(item->{
            this.packUserInfo(item);
        });

        return pageModel;
    }

    //根据用户id锁定解锁
    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //1根据id查询用户
        UserInfo userInfo = this.packUserInfo(baseMapper.selectById(userId)) ;
        //2根据userId查询就诊人列表
        List<Patient>patientList = patientService.findAllByUserId(userId);
        //3封装返回
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    //实现编码翻译
    private UserInfo packUserInfo(UserInfo userInfo){
        //处理认证状态编码
        String authStatusString =
                AuthStatusEnum.getStatusNameByStatus(userInfo.getStatus());
        userInfo.getParam().put("authStatusString",authStatusString);
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
